import { inlineSource as inline } from 'inline-source';
import JsReport from 'jsreport-core';
import JsreportHtml2Xlsx from 'jsreport-html-to-xlsx';
import JsreportXlsx from 'jsreport-xlsx';

/**
 * html转换为excel
 * @param html 需转换的内容
 * @param attachment 文件名称
 * @example html2pdf(html, attachment);
 */
export default async function html2pdf(html: string, attachment?: string, rootpath = '') {
	const jsreport = JsReport();
	jsreport.use(JsreportXlsx());
	jsreport.use(JsreportHtml2Xlsx());

	const content = await inline(html, {
		compress: true,
		rootpath
	});
	await jsreport.init();
	const resp = await jsreport.render({
		template: {
			content,
			engine: 'none',
			htmlToXlsx: { htmlEngine: 'phantom' },
			recipe: 'html-to-xlsx'
		}
	});
	if (attachment) {
		return {
			attachment,
			buff: resp.content,
			content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'	// application/octet-stream
		};
	} else {
		return {
			buff: resp.content,
			content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		};
	}
}
